<?php

/*
 * Created on 15/09/2008
 *
 * This file is the view to allow a coach to enter or update the details of a match
 */

/* Local Functions */
/**
 * Output Skills
 */
function echoSkillArray($name, $array, $selected = "") {
    echo "<td class=\"vsmall\"><select class=\"vsmall\" name=\"" . $name . "\">\n";
    foreach ($array as $skill) {
        echo "<option value=\"" . $skill->id . "\"";
        if ($skill->id == $selected) {
            echo " selected ";
        }
        echo ">" . $skill->name . "</option>\n";
    }
    echo "</select></td>\n";
}

function getPurchaseArray($low, $high) {
    $array = array ();
    for ($i = $low; $i <= $high; $i++) {
        $array[$i] = $i;
    }
    return $array;
}

/** 
 * Output the fields for a single player 
 */
function echoPlayer(& $player, $row, & $matchRecord, $race, $pmr = false) {
    if (!$pmr) {
        $pmr = new PlayerMatchRecord($player, $matchRecord);
        $pmr->load();
    }
    $spps = $pmr->getSPPs();
    $startSpps = $player->getSPPs() - $spps;
    echo<<< EOQ
        $row
            <td class="vsmall">#$player->rosterNum $player->name $player->position</td>
EOQ;
    echoSelect("cp" . $player->playerId, 13, $pmr->comps, "onChange=\"updateSPPs('" . $player->playerId . "')\"");
    echoSelect("td" . $player->playerId, 7, $pmr->tds, "onChange=\"updateSPPs('" . $player->playerId . "')\"");
    echoSelect("in" . $player->playerId, 5, $pmr->ints, "onChange=\"updateSPPs('" . $player->playerId . "')\"");
    echoSelect("cs" . $player->playerId, 13, $pmr->cas, "onChange=\"updateSPPs('" . $player->playerId . "')\"");
    echoSelect("mvp" . $player->playerId, 3, $pmr->mvps, "onChange=\"updateSPPs('" . $player->playerId . "')\"");
    echo<<< EOQ
        <td>
        	<input name="spps$player->playerId" type="text" size="2" onfocus="changeFocus('injury$player->playerId')" value="$spps" />
        </td>
        <td class="vsmall">
        	<i>($startSpps)</i>
        </td>
EOQ;
    $position = $race->getPosition($player->position);
    if ($position) {
        $skills = array_key_diff($position->getAvailableSkills(), $player->getSkills($race));
    } else {
        $skills = array ();
    }
    array_unshift($skills, new Skill(array (
        "0" => 0,
        "",
        ""
    )));

    $selected = 0;
    if ($pmr->hasSkill()) {
        $skills[$pmr->skill->id] = $pmr->skill;
        $selected = $pmr->skill->id;
    }
    echoSkillArray("skill" . $player->playerId, $skills, $selected);
    echo "<td class=\"vsmall\">";
    echoSelectArray("injury" . $player->playerId, $pmr->getInjuryTypes(), $pmr->injury, "", "class=\"vsmall\"");
    echo<<< EOQ
    		</td>
        </tr>
EOQ;
}

function echoPurchasePositionRow(& $matchRecord, $i, & $team, & $mpp, $next = 0) {
    $race = & $team->race;
    echo<<< EOQ
		<tr>
EOQ;
    echo "<td><select name=\"roster_num" . $matchRecord->id . "_" . $i . "\">";
    for ($r = 1; $r < 17; $r++) {
        echo "<option value=\"$r\"";
        if ((isset ($mpp->rosterNum) and $r == $mpp->rosterNum) || $next == $r) {
            echo " selected";
        }
        echo ">$r</option>";
    }
    echo "</select></td>\n";
    echo "<td><select name=\"position" . $matchRecord->id . "_" . $i . "\"  onChange=\"updateRow('" . $matchRecord->id . "', '" . $i . "')\">\n<option value=\"\" selected>&nbsp;</option>\n";
    foreach ($race->positions as $position) {
        echo "<option value=\"" . $position->id . "\"";
        if (isset($mpp) && isset($mpp->position) && $mpp->position->id == $position->id) {
            echo " selected";
        }
        echo ">" . $position->position . "</option>\n";
    }
    echo "</select></td>";
    echo "<td align=left><input name=\"name" . $matchRecord->id . "_" . $i . "\" type=\"text\" size=\"22\" maxlength=\"64\" value=\"" . $mpp->name . "\"/></td>\n";
    echo "<td align=left><input name=\"positioncost" . $matchRecord->id . "_" . $i . "\" type=\"text\" size=\"3\" maxlength=\"3\" value=\"" . $mpp->cost . "\"/></td>\n";
    echo<<< EOQ
		</tr>
EOQ;

}

/**
 * Output the details of a whole team
 */
function echoTeamDetails(& $team, & $matchRecord) {
    $race = $team->race;
    $numPositions = sizeof($race->positions);
    echo<<< EOQ
    <script language="JavaScript">
    //Create a new array named positionList with some elements.
    positionList$matchRecord->id = new BuildZeroArray($numPositions)   //Create empty product list array.
    positionList$matchRecord->id[0] = new position('', '')

EOQ;
    $posNum = 1;
    foreach ($team->race->positions as $position) {
        $cost = $position->cost;
        if ($position->isJourneyman() or $position->isStar()) {
            $cost = 0;
        }
        echo "positionList$matchRecord->id[" . $posNum++ . "] = new position('" . $position->position . "', " . $cost . ")\n";
    }
    echo<<< EOQ
    </script>
    <table border="0" cellspacing="0" cellpadding="1">
        <tr>
            <th colspan="10">$team->name</th>
        </tr>
        <tr>
            <th>Player</th>
            <th><span title="Completions">CP</span></th>
            <th><span title="Touchdowns">TD</span></th>
            <th><span title="Interceptions">IN</span></th>
            <th><span title="Casualties">CS</span></th>
            <th><span title="MVP">MVP</span></th>
            <th colspan="2"><span title="Star Player Points for the Game (starting SPPs). These cannot be edited">SPPs</span></th>
            <th><span title="Skill gained during the game">Skill</span></th>
            <th><span title="Injury">Injury</span></th>
        </tr>
EOQ;
    // Players first
    $count = 0;
    $pmrDao = new PlayerMatchRecordDao();
    $pmrs = $pmrDao->getPMRsForMatch($matchRecord);
    foreach ($pmrs as $pmr) {
        $row = getEchoTR($count++);
        echoPlayer($pmr->player, $row, $matchRecord, $race, $pmr);
    }

    for ($i = 1; $i < 17; $i++) {
        $player = $team->getPlayer($i);
        if ($player and !isset ($pmrs[$player->playerId])) {
            $matched = false;
            foreach ($matchRecord->getPurchases() as $mpp) {
                if ($mpp->isSameAs($player)) {
                    $matched = true;
                    break;
                }
            }
            if (!$matched) {
                $row = getEchoTR($count++);
                echoPlayer($player, $row, $matchRecord, $race);
            }
        }
    }
    $mup = new MatchUpdater();
    $tv = $team->getTR();
    $spiralling = $mup->calcSpirallingExpenses($tv);
    echo<<< EOQ
		<tr>
			<th>Winnings</th>
			<td colspan="8">
EOQ;
    echoWinnings("winnings" . $matchRecord->id, $matchRecord->winnings);
    $mup = new MatchUpdater();
    $tv = $team->getTR();
    $spiralling = $mup->calcSpirallingExpenses($tv);
    $treasury = $team->treasury;
    $spirallingShow = "0";
    if ($spiralling > 0) {
        $spirallingShow = $spiralling . ",000";
    }
    if ($treasury > 0) {
        $treasury = $treasury . ",000";
    }
    echo<<< EOQ
			 Spiralling Expenses: \$$spirallingShow
			 Treasury: \$$treasury
		 </td>
		</tr>
		<tr>
			<th>Fans</th>
			<td colspan="8">
EOQ;
    echoFans("fans" . $matchRecord->id, $matchRecord->fanFactor);
    echo<<< EOQ
			</td>
		</tr>
		<tr>
			<th colspan="9">Purchases</th>
		</tr>
		<tr>
			<td colspan="9">
				<table border="0" cellspacing="0" cellpadding="3">
		<tr>
			<th>#</th>
			<th>Position</th>
			<th>Name</th>
			<th>\$</th>
		</tr>
EOQ;
    $i = 1;
    foreach ($matchRecord->getPurchases() as $mpp) {
        echoPurchasePositionRow($matchRecord, $i++, $team, $mpp);
    }
    $availables = array ();
    for ($r = 1; $r < 17; $r++) {
        $player = $team->getPlayer($r);
        if (!$player) {
            array_push($availables, $r);
        } else {
        	if (isset($pmrs[$player->playerId])) {
            $pmr = $pmrs[$player->playerId];
	            if (isset ($pmr)) {
	                if (0 == strcmp("Dead", $pmr->injury)) {
	                    array_push($availables, $r);
	                }
	            } else {
	                array_push($availables, $r);
	            }
        	}
        }
    }
    $availables = array_reverse($availables);
    for (; $i < 6; $i++) {
        $next = 0;
        if (count($availables) > 0) {
            $next = array_pop($availables);
        }
        echoPurchasePositionRow($matchRecord, $i, $team, new MatchPositionPurchase(), $next);
    }
    echo<<< EOQ
    		</table>
		</tr>
		<tr>
			<td colspan="9">
				<table border="0" cellspacing="0" cellpadding="3">
		<tr>
			<th>Rerolls</th>			
			<td>
EOQ;
    $teamRRCost = 2 * $race->rerollCost;
    $rrCost = $matchRecord->rerolls * $teamRRCost;
    if ($rrCost < 0)
        $rrCost = 0;
    $acCost = $matchRecord->coaches * 10;
    if ($acCost < 0)
        $acCost = 0;
    $clCost = $matchRecord->cheerleaders * 10;
    if ($clCost < 0)
        $clCost = 0;
    $apoCost = $matchRecord->apothecary * 50;
    if ($apoCost < 0)
        $apoCost = 0;
    $totalCost = $rrCost + $acCost + $clCost + $apoCost;

    echoSelectArray("rr" . $matchRecord->id, getPurchaseArray(-1 * $team->rerolls, 2), $matchRecord->rerolls, "onChange=\"updateRRCost('" . $matchRecord->id . "', " . $teamRRCost . ")\"");
    echo<<< EOQ
			<td>@ $teamRRCost,000 = </td>
	        <td>
	        	<input name="rrCost$matchRecord->id" type="text" size="2" onfocus="changeFocus('ac$matchRecord->id')" value="$rrCost" />
	        </td>
		</tr>
		<tr>
			<th>Assistant Coaches</th>
			<td>
EOQ;
    echoSelectArray("ac" . $matchRecord->id, getPurchaseArray(-1 * $team->coaches, 9), $matchRecord->coaches, "onChange=\"updatePurchase('ac" . $matchRecord->id . "', 'acCost" . $matchRecord->id . "', '" . $matchRecord->id . "')\"");
    echo<<< EOQ
			<td>@ 10,000 = </td>
	        <td>
	        	<input name="acCost$matchRecord->id" type="text" size="2" onfocus="changeFocus('cl$matchRecord->id')" value="$acCost" />
	        </td>
		</tr>
		<tr>
			<th>Cheerleaders</th>
			<td>
EOQ;
    echoSelectArray("cl" . $matchRecord->id, getPurchaseArray(-1 * $team->cheerleaders, 9), $matchRecord->cheerleaders, "onChange=\"updatePurchase('cl" . $matchRecord->id . "', 'clCost" . $matchRecord->id . "', '" . $matchRecord->id . "')\"");
    echo<<< EOQ
			<td>@ 10,000 =</td>
	        <td>
	        	<input name="clCost$matchRecord->id" type="text" size="2" onfocus="changeFocus('apo$matchRecord->id')" value="$clCost" />
	        </td>
		</tr>
		<tr>
			<th>Apothecary</th>
			<td>
EOQ;
    echoSelectArray("apo" . $matchRecord->id, getPurchaseArray(-1 * $team->apothecary, 1), $matchRecord->apothecary, "onChange=\"updateApoCost('" . $matchRecord->id . "')\"");
    echo<<< EOQ
			<td>@ 50,000 =</td>
	        <td>
	        	<input name="apoCost$matchRecord->id" type="text" size="2" onfocus="changeFocus('totalCost$matchRecord->id')" value="$apoCost" />
	        </td>
		</tr>
		<tr>
			<th>Spent</th>
			<th colspan="2"><input name="totalCost$matchRecord->id" type="text" size="2" onfocus="changeFocus('rr$matchRecord->id')" value="$totalCost" /></th>
		</tr>
    </table></td></tr>
    </table>
EOQ;

}

/**
 * Update an individal match record after a post
 */
function updateMatchRecord(& $matchRecord, & $team) {
    global $_POST;
    $matchRecord->score = getVariable("tds", $matchRecord->id, $_POST);
    $matchRecord->casualties = getVariable("cas", $matchRecord->id, $_POST);
    $matchRecord->winnings = getVariable("winnings", $matchRecord->id, $_POST);
    $matchRecord->fanFactor = getVariable("fans", $matchRecord->id, $_POST);
    $matchRecord->rerolls = getVariable("rr", $matchRecord->id, $_POST);
    $matchRecord->apothecary = getVariable("apo", $matchRecord->id, $_POST);
    $matchRecord->cheerleaders = getVariable("cl", $matchRecord->id, $_POST);
    $matchRecord->coaches = getVariable("ac", $matchRecord->id, $_POST);
    $matchRecord->purchases = array ();
    for ($i = 1; $i < 6; $i++) {
        $position = getVariable("position" . $matchRecord->id . "_", $i, $_POST);
        if (isset ($position) and $position > 0) {
            $mpp = new MatchPositionPurchase();
            $mpp->rosterNum = getVariable("roster_num" . $matchRecord->id . "_", $i, $_POST);
            $mpp->name = getVariable("name" . $matchRecord->id . "_", $i, $_POST);
            $mpp->position = $team->race->getPositionById($position);
            array_push($matchRecord->purchases, $mpp);
        }
    }
    $rs = $matchRecord->update();
    if ($rs <> 1) {
        echo<<< EOQ
		<tr><td colspan="2" class="error">Unable to update match record due to:<br />$rs</td></tr>
EOQ;
    }
    return;
}

/**
 * Update a player after a post
 */
function updatePlayer(& $player, & $matchRecord, $pmr = false) {
    global $_POST, $skills;
    $exists = true;
    if (!$pmr) {
        $pmr = new PlayerMatchRecord($player, $matchRecord);
        $exists = $pmr->load();
    }
    $pmr->comps = getVariable("cp", $player->playerId, $_POST);
    $pmr->cas = getVariable("cs", $player->playerId, $_POST);
    $pmr->tds = getVariable("td", $player->playerId, $_POST);
    $pmr->ints = getVariable("in", $player->playerId, $_POST);
    $pmr->mvps = getVariable("mvp", $player->playerId, $_POST);
    $injuryKey = getVariable("injury", $player->playerId, $_POST);
    $injuries = $pmr->getInjuryTypes();
    $pmr->injury = $injuries[$injuryKey];
    $skillKey = getVariable("skill", $player->playerId, $_POST);
    if (isset ($skillKey) and $skillKey) {
        $pmr->skill = $skills[$skillKey];
    } else
        if ($pmr->hasSkill()) {
            $pmr->skill = NULL;
        }
    $pmr->save();
}

/**
 * Update a team after a post
 */
function updateTeam(& $team, & $matchRecord) {
    updateMatchRecord($matchRecord, $team);
    $pmrDao = new PlayerMatchRecordDao();
    $pmrs = $pmrDao->getPMRsForMatch($matchRecord);
    foreach ($pmrs as $pmr) {
        updatePlayer($pmr->player, $matchRecord, $pmr);
    }
    for ($i = 1; $i < 17; $i++) {
        $player = $team->getPlayer($i);
        if ($player and !isset ($pmrs[$player->playerId])) {
            updatePlayer($player, $matchRecord);
        }
    }

}

function updateMatch(& $match, & $homeTeam, & $awayTeam, $applyUpdate = false) {
    global $_POST;
    $match->type = $_POST["matchType"];
    $match->gate = $_POST["gate"];
    updateTeam($homeTeam, $match->homeRec);
    updateTeam($awayTeam, $match->awayRec);
    $errors = array ();
    if ($applyUpdate) {
        $updater = new MatchUpdater();
        $errors = $updater->updateTeams($match, $homeTeam, $awayTeam);
    }
    $md = new MatchDao();
    $md->update($match);
    return $errors;
}

/* 
 * Start of Page 
 */
include_once ("includes/init.php");
include_once ("includes/match_utils.php");

/* Requires logged in user */
if (!isset ($loggedin)) {
    $message = "Permission Denied";
    include ("includes/redirect.php");
    return;
}

/* Requires match Id of match to be updated */
$matchId = getParam("matchId");
if (!isset ($matchId)) {
    $redirect = "results.php";
    $redirectStr = "Match Submission";
    $message = "Unable to identify match to update details of";
    include ("includes/redirect.php");
    return;
}

$submit = getParam("submit");
$update = getParam("update");
$delete = getParam("delete");

$match = $matches->getMatch($matchId);
$homeTeam = $teams->getTeam($match->homeRec->teamId);
$awayTeam = $teams->getTeam($match->awayRec->teamId);
$canEdit = $loggedin->canEditMatch($match);

/* Validate user has appropriate permissions for this match */
if (!$canEdit) {
    $message = "Permission Denied";
    include ("includes/redirect.php");
    return;
}

/* Data is being submitted, update the database */
if (isset ($submit) || isset ($update)) {
    $errors = updateMatch($match, $homeTeam, $awayTeam, isset ($update));
    if (0 == count(($errors))) {
        $redirect = "match_view.php?matchId=$matchId&reload=true";
        $redirectStr = "Updating";
        $message = "Updating the match";
        include ("includes/redirect.php");
        return;
    }
} else
    if (isset ($delete) and isCommissioner()) {
        $md = new MatchDao();
        $md->delete($match);
        $message = "Match Deleted";
        include ("includes/redirect.php");
        return;
    }

/**
 * Main Display Section
 */
$scriptHead = "<script language=\"javascript\">

    // update player SPP totals when one value changed
    function updateSPPs(rownum) {
      var spps = getValue('document.matchDetails.cp'+rownum+'.value');
      spps+=(3 * getValue('document.matchDetails.td'+rownum+'.value'));
      spps+=(2 * getValue('document.matchDetails.in'+rownum+'.value'));
      spps+=(2 * getValue('document.matchDetails.cs'+rownum+'.value'));
      spps+=(5 * getValue('document.matchDetails.mvp'+rownum+'.value'));
      var exeLine='document.matchDetails.spps'+rownum+'.value=spps';
      eval (exeLine);
    }
    
    function updateRRCost(rownum, cost) {
      var rrs = getValue('document.matchDetails.rr'+rownum+'.value');
      rrs=rrs * cost;
      if (rrs < 0) {
         rrs = 0;
      }
      var exeLine='document.matchDetails.rrCost'+rownum+'.value=rrs';
      eval (exeLine);
      updateTotalCost(rownum);
    }
    
    function updateApoCost(rownum) {
      var cost = getValue('document.matchDetails.apo'+rownum+'.value');
      cost=cost* 50;
      if (cost < 0) {
         cost = 0;
      }
      var exeLine='document.matchDetails.apoCost'+rownum+'.value=cost';
      eval (exeLine);
      updateTotalCost(rownum);
    }
    
    function updatePurchase(source, destination, rownum) {
      var value = 10 * getValue('document.matchDetails.'+source+'.value');
      if (value < 0) {
         value = 0;
      }
      var exeLine='document.matchDetails.'+destination+'.value=value';
      eval (exeLine);
      updateTotalCost(rownum);
    }
    
    function updateTotalCost(mrid) {
      var total  = getValue('document.matchDetails.rrCost'+mrid+'.value');
      total += getValue('document.matchDetails.acCost'+mrid+'.value');
      total += getValue('document.matchDetails.clCost'+mrid+'.value');
      total += getValue('document.matchDetails.apoCost'+mrid+'.value');
      total += getPlayerValue(mrid+'_1');
      total += getPlayerValue(mrid+'_2');
      total += getPlayerValue(mrid+'_3');
      total += getPlayerValue(mrid+'_4');
      total += getPlayerValue(mrid+'_5');
      var exeLine='document.matchDetails.totalCost'+mrid+'.value=total';
      eval (exeLine);
    }
    
    // Extact the value from a field
    function getValue(exeLine)
    {
      var strValue = '';
      var intValue = 0;
      eval ('strValue='+exeLine);
      if (strValue.length != 0) {
        intValue = eval(strValue);
      }
      return intValue;
    }
    
    // Set the focus to the next element
    function changeFocus(rowNum) {
        var exeLine='document.matchDetails.' + rowNum + '.focus()'
        eval (exeLine);
        var exeLine='document.matchDetails.' + rowNum + '.select()'
        eval (exeLine);
    }


    //-- Function to create a new, empty array that starts at zero.
    function BuildZeroArray(n)
    {
       this.length = n
       for (var i=0;i<=n;i++) {this[i]=0}
       return this
    }

    // class to represent a position in Javascript
    function position(name, cost)
    {
       this.name = name
       this.cost = cost
    }


    // update a row when position changes
    function updateRow(mrid, idx)
    {
       var exeLine='PositionSubscript=document.matchDetails.position'+mrid+'_'+idx+'.selectedIndex'
       eval(exeLine)
       var exeLine='document.matchDetails.positioncost'+mrid+'_'+idx+'.value=positionList'+mrid+'[PositionSubscript].cost'
       eval (exeLine);
       updateTotalCost(mrid);
    }


    function getPlayerValue(number) {
        var cost = getValue('document.matchDetails.positioncost' + number + '.value')
        return cost;

    }

</script>
";

$title = $homeTeam->name . " vs " . $awayTeam->name;
include_once ("includes/header.php");
echo<<< EOQ
    <caption><h1>Match Details</h1></caption>
    <form name="matchDetails" method="POST" action="match_edit.php" >
    <input type="hidden" name="matchId" value="$matchId" />
EOQ;
if (isCommissioner()) {
    echo<<< EOQ
<tr>
	<td align="left"><input type="submit" name="delete" value="Delete" /></td>
	<td align="right"><a href="match_view.php?matchId=$match->id">Details</a></td>
</tr>
EOQ;
} else {
    echo<<< EOQ
<tr><td colspan="2" align="right"><a href="match_view.php?matchId=$match->id">Details</a></td></tr>
EOQ;
}
if (isset ($errors)) {
    foreach ($errors as $error) {
        echo<<< EOQ
<tr><td colspan="2" class="error">$error</td></tr>
EOQ;
    }
}
$rowcount = 0;
echo<<< EOQ
<tr><td colspan="2">
<table width="100%" cellspacing="0" cellpadding="2">
<tr>
  <th align="center" class="strong">Date</th>
  <th align="center" class="strong">Home</th>
  <th align="center" class="strong">&nbsp;</th>
  <th align="center" class="strong">Away</th>
  <th align="center" class="strong">Gate</th>
  <th align="center" class="strong">&nbsp;</th>
</tr>
EOQ;
echo getEchoTR(++ $rowcount);
echo "\n<th align=center rowSpan=2>" . getEchoValue($match->datePlayed) . "</th>\n";
echo "<td align=center rowSpan=2><b>" . getEchoValue($homeTeam->getRosterLink()) . "<br />(" . getEchoValue($homeTeam->coach->getName()) . ")</b></td>\n";
echo "<th align=center>";
echoSelect("tds" . $match->homeRec->id, 17, $match->homeRec->score, "", false);
echo "&nbsp;TDs&nbsp;";
echoSelect("tds" . $match->awayRec->id, 17, $match->awayRec->score, "", false);
echo "</th>\n";
echo "<td align=center rowSpan=2><b>" . getEchoValue($awayTeam->getRosterLink()) . "<br />(" . getEchoValue($awayTeam->coach->getName()) . ")</b></td>\n";
echo "<td align=center>";
echoSelectArray("matchType", $match->getMatchTypes(), $match->type);
echo "</td></tr>\n";
echo getEchoTR($rowcount);
echo "<td align=center><font size=-1>";
echoSelect("cas" . $match->homeRec->id, 17, $match->homeRec->casualties, "", false);
echo "\n";
echo "&nbsp;Cas&nbsp;";
echoSelect("cas" . $match->awayRec->id, 17, $match->awayRec->casualties, "", false);
echo<<< EOQ
 	</font></td>
		<td align="center">
			<input type="text" name="gate" value="$match->gate" maxlength="8" size="8"/>
		</td>
	</tr>
EOQ;
showComments($rowcount, $match->homeRec->comments, $homeTeam->coach, $match->awayRec->comments, $awayTeam->coach, false);
echo getEchoTR($rowcount);
echo<<< EOQ
	<td colspan="7">&nbsp;</td></tr></table></td></tr>
    <tr>
        <td valign="top">
        <!-- Home Team Details -->
EOQ;
echoTeamDetails($homeTeam, $match->homeRec);
echo<<< EOQ
        </td>
        <td valign="top">
        <!-- Away Team Details -->
EOQ;
echoTeamDetails($awayTeam, $match->awayRec);

// IF teams already updated save only 
// IF no approvals and teams updated save only
// IF no approvals and NOT teams updated apply and save
// IF approvals and teams updated - save only
// IF approvals and teams not updated - save only 
$ad = new ApprovalDao();
$approvals = $ad->findMatchApprovals($match);
if ($approvals) {
    $approvals = count($approvals);
}
$saveOnly = $match->teamsUpdated || $approvals;
echo<<< EOQ
        </td>
    </tr>
    <tr class="row2">
        <td colspan="2" align="center">
            <input type="submit" name="submit" value="Save" title="Save changes to the match details"/>
EOQ;
if (!$saveOnly) {
    echo<<< EOQ
            <input type="submit" name="update" value="Save and Update Teams" title="Save changes to the match details and update the teams"/>
EOQ;
}
echo<<< EOQ
        </td>
    </tr>
    </form>
EOQ;
?>
